package auth

import (
	"admin/dao/auth"
	"admin/dto"
	"admin/modules/auth/logic"
	"admin/utils"
	"admin/utils/response"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"strconv"
)

type PermissionController struct {
	permissionLogic *logic.PermissionLogic
}

func NewPermissionController(db *gorm.DB) *PermissionController {
	permissionRepo := auth.NewPermissionRepo(db)
	return &PermissionController{
		permissionLogic: logic.NewPermissionLogic(permissionRepo),
	}
}

// List 获取权限列表
func (p *PermissionController) List(c *gin.Context) {
	req, _ := utils.BindJson[dto.PermissionListReq](c)
	list, err := p.permissionLogic.List(req)
	if err != nil {
		response.Error(c, http.StatusBadRequest, 1002, err.Error(), "获取失败")
		return
	}
	response.OK(c, gin.H{"list": list}, "success", "成功")
}

// Create 创建权限
func (p *PermissionController) Create(c *gin.Context) {
	req, _ := utils.BindJson[dto.PermissionDto](c)
	err := p.permissionLogic.Create(req)
	if err != nil {
		response.Error(c, http.StatusBadRequest, 1002, err.Error(), "创建失败")
		return
	}
	response.OK(c, gin.H{}, "success", "成功")
}

// Update 更新权限
func (p *PermissionController) Update(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	req, _ := utils.BindJson[dto.PermissionDto](c)
	if err := p.permissionLogic.Update(id, req); err != nil {
		response.Error(c, http.StatusBadRequest, 1002, err.Error(), "更新失败")
		return
	}
	response.OK(c, gin.H{}, "success", "成功")
}

// GetPermissionByID 通过ID获取权限
func (p *PermissionController) GetPermissionByID(ctx *gin.Context) {
	pid, _ := strconv.ParseInt(ctx.Param("id"), 10, 64)
	permission, err := p.permissionLogic.GetPermissionByID(pid)
	if err != nil {
		response.Error(ctx, http.StatusBadRequest, 1002, err.Error(), "获取失败")
		return
	}
	response.OK(ctx, gin.H{"permission": permission}, "success", "成功")
}

// Delete 删除权限
func (p *PermissionController) Delete(c *gin.Context) {
	id, _ := strconv.ParseInt(c.Param("id"), 10, 64)
	if err := p.permissionLogic.Delete(id); err != nil {
		response.Error(c, http.StatusBadRequest, 1002, err.Error(), "删除失败")
		return
	}
	response.OK(c, gin.H{}, "success", "成功")
}
